/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fxification.java;

import com.sun.javafx.functions.Function0;
import com.sun.javafx.functions.Function1;
import java.lang.Thread.UncaughtExceptionHandler;

/**
 *
 * @author vvivien
 */
public class SimpleTaskRunner extends ATaskRunner{
    private Thread thread;
    @Override
    public void run(final TaskRunnerContext task) {
        if(task.getTaskWork() == null){
            throw new RuntimeException("Task has no work to be performed.  Provide a work function().");
        }

        if(task.isStarted()){
            return;
        }

        thread = new Thread(new Runnable(){
            @Override
            public void run() {
                signalTaskStart(task);
                Object result = task.getTaskWork().invoke();
                signalTaskCompletion(task, result);
            }
        }, "FxTaskRunner-"+Thread.currentThread().getId());

        thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                signalTaskError(task,e);
            }
        });
        thread.start(); // start new thread for task.
    }

    @Override
    public void stop(TaskRunnerContext task) {
        thread.interrupt();
        signalTaskStop(task);
    }

}
